package com.easyoffer.exception;

import cn.dev33.satoken.exception.*;
import com.easyoffer.common.BaseResponse;
import com.easyoffer.common.ErrorCode;
import com.easyoffer.common.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.dao.DuplicateKeyException;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 拦截：未登录异常
    @ExceptionHandler(NotLoginException.class)
    public BaseResponse<Object> handlerException(NotLoginException e) {

        // 打印堆栈，以供调试
        e.printStackTrace();

        // 返回给前端
        return ResultUtils.error(e.getCode(),e.getMessage());
    }

    // 拦截：缺少权限异常
    @ExceptionHandler(NotPermissionException.class)
    public BaseResponse<Object>  handlerException(NotPermissionException e) {
        e.printStackTrace();
        return ResultUtils.error(e.getCode(),"缺少权限" + e.getPermission());
    }

    // 拦截：缺少角色异常
    @ExceptionHandler(NotRoleException.class)
    public BaseResponse<Object> handlerException(NotRoleException e) {
        e.printStackTrace();
        return ResultUtils.error(e.getCode(),"缺少角色" + e.getRole());
    }

    // 拦截：二级认证校验失败异常
    @ExceptionHandler(NotSafeException.class)
    public BaseResponse<Object> handlerException(NotSafeException e) {
        e.printStackTrace();
        return ResultUtils.error(e.getCode(),"二级验证失败" + e.getService());
    }

    // 拦截：服务封禁异常
    @ExceptionHandler(DisableServiceException.class)
    public BaseResponse<Object> handlerException(DisableServiceException e) {
        e.printStackTrace();
        return ResultUtils.error(e.getCode(),
                "当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封");
    }

    // 拦截：Http Basic 校验失败异常
    @ExceptionHandler(NotHttpBasicAuthException.class)
    public BaseResponse<Object> handlerException(NotHttpBasicAuthException e) {
        e.printStackTrace();
        return ResultUtils.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(BusinessException.class)
    public Object handlerBusinessException(BusinessException e) {
        log.error("业务异常", e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Object handlerDuplicateKeyException(DuplicateKeyException e) {
        log.error("数据库重复异常", e);
        return ResultUtils.error(ErrorCode.OPERATION_ERROR.getCode(), "重复添加数据");
    }
    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e) {
        log.error("系统异常", e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMessage());
    }
}
